
var dataWorkPhoneExt = '';
var focusWorkPhone = false;

// Create new model to apply to view
var CompanySettingsModel = new function () {

    // Show popup when credit card declined
    this.TotalPriceProduct = ko.observable(data.TotalPriceProduct);
    this.HasCreditDeclinde = ko.observable(false);
    this.ShowPrevious = ko.computed(function () {
        return (this.HasCreditDeclinde() == true ? false : true);
    }, this);

    if (data.CardDeclined == false) {
        this.HasCreditDeclinde(true);
        init_popupCredit();
    }

    // General info
    this.CompanyName = ko.observable(data.GeneralSettingsInfo.CompanyName)
		.extend({ maxLength: 50 })
		.extend({ required: { message: "Company Name is required"} })
		.extend({ pattern: { message: 'This field cannot contain special characters', params: '^[^<>]*$'} });


    // Split phone string int0 'cell' variable
    var cell1 = '', cell2 = '', cell3 = '', cell4 = '';
    if (data.GeneralSettingsInfo.PhoneNumber != null) {
        var phoneValue = data.GeneralSettingsInfo.PhoneNumber;
        phoneValue = phoneValue.replace("(", "");
        phoneValue = phoneValue.replace(")", "");
        phoneValue = phoneValue.replace("-", " ");
        phoneValue = phoneValue.replace("x", "");

        var phoneSplit = phoneValue.split(' ');
        var phoneArray = new Array();
        var indexArray = 0;

        for (var i = 0; i < phoneSplit.length; i++) {
            if ($.trim(phoneSplit[i]) != '') {
                phoneArray[indexArray] = phoneSplit[i];
                indexArray++;
            }
        }

        if (phoneArray.length > 0) {
            cell1 = phoneArray[0];
        }

        if (phoneArray.length > 1) {
            cell2 = phoneArray[1];
        }

        if (phoneArray.length > 2) {
            cell3 = phoneArray[2];
        }

        if (phoneArray.length > 3) {
            cell4 = phoneArray[3];
        }
    }

    dataWorkPhoneExt = cell4;

    var extDefault = 'Ext.';
    if (cell4 != "") {
        this.WorkPhoneExt = ko.observable(cell4);
    } else {
        this.WorkPhoneExt = ko.observable(extDefault);
        $("#WorkPhoneExt").attr("value", extDefault);
    }

    this.CellPhone1 = ko.observable(cell1);
    this.CellPhone2 = ko.observable(cell2);
    this.CellPhone3 = ko.observable(cell3);

    this.WorkPhone = ko.computed(function () {
        return this.CellPhone1() + this.CellPhone2() + this.CellPhone3();
    }, this).extend({ minLength: { params: 10, message: "Enter a valid phone number" },
        maxLength: { params: 10, message: "Enter a valid phone number" },
        required: { message: "Phone number is required" }
    }).extend({ phoneUS: { message: "Enter a valid phone number"} });

    // Each input
    $(":input").focus(function () {
        var id = $(this).attr("id");

        // group 1
        if (id == "cell1" || id == "cell2" || id == "cell3") {
            $("#cell1").parent('.input-holder-setup').find('.error-desc').remove();
            var message = $(this).parents(".groupinput").find('.error-desc');
            // group message
            if (focusWorkPhone) {
                message.show();
            }
            else {
                message.hide();
            }
        }

        if (id == "WorkPhoneExt") {
            if ($("#WorkPhoneExt").val() == extDefault) {
                $("#WorkPhoneExt").val("");
            }
        }
    });

    $(":input").focusout(function () {
        var id = $(this).attr("id");

        var phone = $('#WorkPhone').val();
        if (id == "cell1" || id == "cell2" || id == "cell3") {
            $("#cell1").parent('.input-holder-setup').find('.error-desc').remove();
            var message = $(this).parents(".groupinput").find('.error-desc');
            // group message
            if (phone.length == 10 && message.text() == '') {
                message.hide();
                focusWorkPhone = true;
            }
            else {
                message.show();
                focusWorkPhone = false;
            }
        }

        if (id == "WorkPhoneExt") {
            if (($("#WorkPhoneExt").val() == null) || ($("#WorkPhoneExt").val() == '')) {
                $("#WorkPhoneExt").val(extDefault);
            }
        }
    });

    //this.PhoneNumber = ko.observable(data.GeneralSettingsInfo.PhoneNumber)
    //	.extend({ required: { message: "Phone Number is required"} });


    this.TimeZoneOptions = ko.observableArray(data.TimeZoneList);
    this.TimeZone = ko.observable(data.GeneralSettingsInfo.TimeZone);
    this.HasNewLeadNotification = ko.observable(data.GeneralSettingsInfo.NewLeadNotificaton);

    // Current service info
    this.NumberOfLicenses = ko.observable(data.CurrentServicesInfo.NumberOfLicenses);
    this.DialIq = ko.computed(function () {
        if (data.CurrentServicesInfo.DialIq != null && data.CurrentServicesInfo.DialIq == true) {
            return "Yes";
        }
        else {
            return "No";
        }
    }, this);

    // Payment Credit info
    if (data.PaymentInfo.CreditModel.CardNumberMask == '' || data.PaymentInfo.CreditModel.CardNumberMask == null) {
        this.CardNumber = ko.observable(data.PaymentInfo.CreditModel.CardNumberMask)
        .extend({ required: { message: "Credit card number is required"} })
        .extend({ pattern: { message: 'Please correct credit card number',
            params: "^(5[1-5]\\d{14}|4\\d{15}|3[47]\\d{13}|[*][*][*][*][ ][*][*][*][*][ ][*][*][*][*][ ]\\d{3,4})$"
        }
        });
    }
    else {
        this.CardNumber = ko.observable(data.PaymentInfo.CreditModel.CardNumberMask)
        .extend({ pattern: { message: 'Please correct credit card number',
            params: "^(5[1-5]\\d{14}|4\\d{15}|3[47]\\d{13}|[*][*][*][*][ ][*][*][*][*][ ][*][*][*][*][ ]\\d{3,4})$"
        }
        });
    }

    this.NameCard = ko.observable(data.GeneralSettingsInfo.FullName)
		.extend({ maxLength: 50 })
		.extend({ required: { message: "Name on credit card is required"} })
		.extend({ pattern: { message: 'This field cannot contain special characters', params: '^[^<>]*$'} });
    this.SecurityCode = ko.observable(data.PaymentInfo.CreditModel.SecurityCode)
        .extend({
            minLength: { params: 3, message: "Please enter 3 or 4 characters" },
            maxLength: { params: 4, message: "Please enter 3 or 4 characters" }
            /*required: { message: "Security Code is required" }*/
        });

    var monthCredit = '';
    var yearCredit = '';

    if (data.PaymentInfo.CreditModel != null) {
        if (data.PaymentInfo.CreditModel.ExpirationDate != null) {
            var dateArray = data.PaymentInfo.CreditModel.ExpirationDate.split(' ');
            monthCredit = $.trim(dateArray[0]);
            yearCredit = $.trim(dateArray[1]);
        }
    }

    this.MonthOptions = ko.observableArray(data.MonthList);
    this.Month = ko.observable().extend({ required: { message: "Month is required"} });

    if (monthCredit != '') {
        this.Month(monthCredit);
    }

    this.YearOptions = ko.observableArray(data.YearList);
    this.Year = ko.observable().extend({ required: { message: "Year is required"} });

    if (yearCredit != '') {
        this.Year(yearCredit);
    }

    // Payment Billing info
    this.BilingAddress1 = ko.observable(data.PaymentInfo.BillingModel.Address1)
		.extend({ maxLength: 250 })
		.extend({ required: { message: "Address is required"} })
		.extend({ pattern: { message: 'Invalid Characters', params: '^[^<>]*$'} });
    this.BilingAddress2 = ko.observable()
		.extend({ pattern: { message: 'Invalid Characters', params: '^[^<>]*$'} });
    this.City = ko.observable(data.PaymentInfo.BillingModel.City)
		.extend({ required: { message: "City is required"} })
		.extend({ pattern: { message: 'Invalid Characters', params: '^[^<>]*$'} });
    //    this.ZipCode = ko.observable(data.PaymentInfo.BillingModel.Zip)
    //		.extend({ maxLength: 100 })
    //		.extend({ required: { message: "Zip code is required"} })
    //		.extend({ pattern: { message: 'Invalid Zip', params: '^[0-9 -]*$'} });

    this.ZipCode = ko.observable(data.PaymentInfo.BillingModel.Zip)
        .extend({
            minLength: { params: 5, message: "Please enter 5 characters" },
            maxLength: { params: 5, message: "Please enter 5 characters" },
            required: { message: "Zip code is required." }
        });

    this.LoadFirstPage = ko.validatedObservable(false);
    this.StateOptionsInfo = ko.observableArray(data.CountryStateList.States.State);
    this.StateOptionsUS = ko.observableArray(ko.utils.arrayFilter(data.CountryStateList.States.State, function (option) {
        return option.ParentId == 194;
    }));

    this.CountryOptions = ko.observableArray(data.CountryStateList.Countries.Country);
    this.Country = ko.observable(194);

    this.StateOptions = ko.observableArray(this.StateOptionsUS());
    this.State = ko.observable(data.PaymentInfo.BillingModel.State).extend({ required: { message: "State is required"} });

    this.StateList = ko.computed(function () {
        var strCountry = this.Country();
        var _State = ko.utils.arrayFilter(this.StateOptionsInfo(), function (option) {
            return option.ParentId == strCountry;
        });
        if (this.LoadFirstPage()) {
            this.StateOptions(_State);

            // Refresh JCF dropdown box
            var tempEl = document.getElementById("State");
            if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
            jcf.customForms.replaceElement("State");
            // Must be executed after knockout rendering
            setTimeout("jcf.customForms.replaceElement('State')", 0);

            if (_State.length > 0) {
                this.State(_State[0].Id);
                $("#State").parent().find(".select-select1").removeClass("select-error");
            }
            else {
                this.State("");
            }
            if ($("#State").hasClass("error")) {
                //alert("a");
                $("#State").removeAttr("select1 jcf-hidden error")
					.removeClass("error")
					.parent().find(".select-select1").removeClass("select-error");
                $("#State").parent().find('.select-select1').removeClass('select-error-margintop20');
                $("#State").parent().find(".error-desc").attr("style", "display: none");
            }
        }
        else {
            this.LoadFirstPage(true);
        }

    }, this);

    this.msgError = ko.observable('');
    this.msgPaymentStatus = ko.observable('');

    this.UpdateCompanySettings = function () {

        //check country & state
        if ($.trim(CompanySettingsModel.Country()) == "") {
            $('#State').removeAttr("select1 jcf-hidden")
				.addClass("select1 jcf-hidden error")
				.parent().find('.select-select1').addClass('select-error-margintop20');
        }

        if ($.trim(CompanySettingsModel.State()) == "") {
            var strCountry = this.Country();
            var _State = ko.utils.arrayFilter(this.StateOptionsInfo(), function (option) {
                return option.ParentId == strCountry;
            });
            if (_State.length > 1) {
                $('#State').removeAttr("select1 jcf-hidden")
        		.addClass("select1 jcf-hidden error")
        		.parent().find('.select-select1').addClass('select-error-margintop20');
                $("#State").parent().find(".error-desc").attr("style", "display: block");
            }
        }
        var abc = CompanySettingsModel.errors();
        var _errors = CompanySettingsModel.errors().length;
        if (CompanySettingsModel.State() == '' && $("#State").hasClass("error") == false) {
            _errors = _errors - 1;
        }

        if (_errors == 0) {

            // Write an ajax function to post userinfo to server
            // Using jquery json post
            var _data = data;

            var ext = CompanySettingsModel.WorkPhoneExt();
            if (ext == extDefault) {
                ext = '';
            }

            _data.GeneralSettingsInfo.CompanyName = CompanySettingsModel.CompanyName();
            _data.GeneralSettingsInfo.PhoneNumber = CompanySettingsModel.WorkPhone() + ext;
            _data.GeneralSettingsInfo.TimeZone = CompanySettingsModel.TimeZone();
            _data.GeneralSettingsInfo.NewLeadNotificaton = CompanySettingsModel.HasNewLeadNotification();

            var cardNumber = $('#CardNumber').val();
            if (cardNumber.indexOf('*') != -1) {
                cardNumber = '';
            }

            var address2 = CompanySettingsModel.BilingAddress2();
            if (address2 == null || address2 == undefined || address2 == '') {
                address2 = '';
            }
            else {
                address2 = ' ' + address2;
            }

            _data.PaymentInfo.CreditModel.CardNumber = cardNumber;
            _data.PaymentInfo.CreditModel.NameCard = CompanySettingsModel.NameCard();
            _data.PaymentInfo.CreditModel.SecurityCode = CompanySettingsModel.SecurityCode();
            _data.PaymentInfo.CreditModel.ExpirationDate = CompanySettingsModel.Month() + ' ' + CompanySettingsModel.Year();
            _data.PaymentInfo.BillingModel.Address1 = CompanySettingsModel.BilingAddress1() + ' ' + address2;
            _data.PaymentInfo.BillingModel.City = CompanySettingsModel.City();
            _data.PaymentInfo.BillingModel.Country = CompanySettingsModel.Country();
            _data.PaymentInfo.BillingModel.Zip = CompanySettingsModel.ZipCode();

            //            var _StateOption = ko.utils.arrayFilter(data.CountryStateList.States.State, function (option) {
            //                if (option.Id == thirdModel.State()) {
            //                    return true;
            //                }
            //            });
            //            if (_StateOption[0].Name == 'Select State') {
            //                _StateOption[0].Name = '';
            //            }

            _data.PaymentInfo.BillingModel.State = CompanySettingsModel.State(); //_StateOption[0].Name;

            var modelData = { generalSettingsInfo: _data.GeneralSettingsInfo, paymentInfo: _data.PaymentInfo };

            closePopup();
            openProcess();

            $.ajax({
                type: "POST",
                url: "/CompanySettings/Submit",
                contentType: "application/json; charset=utf-8",
                dataType: "JSON",
                data: JSON.stringify(modelData),
                success: function (model, textStatus, jqXHR) {

                    hideProcess();
                    closePopup();

                    if (model.UpdateStatus == false) {
                        // Error submit
                        CompanySettingsModel.msgError(model.Message);
                        showmsgError();
                    }
                    else {
                        if (model.PaymentStatus == true) {
                            CompanySettingsModel.msgPaymentStatus("Thank you for your payment!");
                        }
                        else {
                            // CompanySettingsModel.msgPaymentStatus(model.Message);
                        }
                        openPopupComplete();
                    }

                },
                error: function (xhr, status, error) {
                    hideProcess();
                    closePopup();
                }
            });

            return true;
        }

        CompanySettingsModel.errors.showAllMessages();
        return false;
    };
};
CompanySettingsModel.errors = ko.validation.group(CompanySettingsModel);

// Apply model
ko.applyBindings(CompanySettingsModel, document.getElementById("CompanySettingsForm"));

function init_popupCredit() {
    closePopup();
	$('#fancybox-overlay').show();
	$('#popupCreditDeclined').showPopup({
		width: 500
	});
}
function openPopupComplete() {
    closePopup();
	$('#fancybox-overlay').show();
	$('#popupComplete').showPopup({
		width: 400
	});
}
function closePopupComplete() {
    closePopup();
    location.reload();
}
function showmsgError() {
    $('#fancybox-overlay').show();
    $('#popupError').showPopup({
        width: 500
    });
}

$(document).ready(function () {

    // Handle all dropdown on-changed events
    var toggleSelect1ErrorMarginTop20 = function () {
        var jObj = $(this);

        if (jObj.hasClass('error')) {
            jObj.parent().find('.select-select1').addClass('select-error-margintop20');
        }
        else {
            jObj.parent().find('.select-select1').removeClass('select-error-margintop20');
        }
    };

    var selectmonth = $('#Month'),
		selectyear = $('#Year');

    selectmonth.parent().find('.error-desc').attr('style', 'display: none');
    selectmonth.parent().find('.select-month-s').removeClass('select-error');
    
    selectmonth.change(function () {
        if (selectmonth.hasClass('error')) {
            selectmonth.parent().find('.select-month-s').addClass('select-error-margintop20');
        }
        else {
            selectmonth.parent().find('.select-month-s').removeClass('select-error-margintop20');
        }

        if (!selectyear.hasClass('error') && !selectmonth.hasClass('error')) {
            selectyear.parent().find('.select-year').removeClass('error');
            selectmonth.parent().find('.select-month-s').removeClass('error');
        }
        else if (!selectyear.hasClass('error') && selectmonth.hasClass('error')) {
            selectyear.parent().find('.select-year').addClass('error');
        }
        else if (selectyear.hasClass('error') && !selectmonth.hasClass('error')) {
            selectmonth.parent().find('.select-month-s').addClass('error');
        }
    });

    selectyear.change(function () {
        if (selectyear.hasClass('error')) {
            selectyear.parent().find('.select-year').addClass('select-error-margintop20');
        }
        else {
            selectyear.parent().find('.select-year').removeClass('select-error-margintop20');
        }

        if (!selectyear.hasClass('error') && !selectmonth.hasClass('error')) {
            selectyear.parent().find('.select-year').removeClass('error');
            selectmonth.parent().find('.select-month-s').removeClass('error');
        }
        else if (!selectyear.hasClass('error') && selectmonth.hasClass('error')) {
            selectyear.parent().find('.select-year').addClass('error');
        }
        else if (selectyear.hasClass('error') && !selectmonth.hasClass('error')) {
            selectmonth.parent().find('.select-month-s').addClass('error');
        }
    });

    $('#btnNext').click(function () {

        // check month
        if (selectmonth.hasClass('error')) {
            selectmonth.parent().find('.select-month-s').addClass('select-error-margintop20');
            selectmonth.parent().find('.error-desc').attr('style', 'display: block');
        }
        else {
            selectmonth.parent().find('.select-month-s').removeClass('select-error-margintop20');
        }

        if (!selectyear.hasClass('error') && !selectmonth.hasClass('error')) {
            selectyear.parent().find('.select-year').removeClass('error');
            selectmonth.parent().find('.select-month-s').removeClass('error');
        }
        else if (!selectyear.hasClass('error') && selectmonth.hasClass('error')) {
            selectyear.parent().find('.select-year').addClass('error');
        }
        else if (selectyear.hasClass('error') && !selectmonth.hasClass('error')) {
            selectmonth.parent().find('.select-month-s').addClass('error');
        }

        // check year
        if (selectyear.hasClass('error')) {
            selectyear.parent().find('.select-year').addClass('select-error-margintop20');
        }
        else {
            selectyear.parent().find('.select-year').removeClass('select-error-margintop20');
        }

        if (!selectyear.hasClass('error') && !selectmonth.hasClass('error')) {
            selectyear.parent().find('.select-year').removeClass('error');
            selectmonth.parent().find('.select-month-s').removeClass('error');
        }
        else if (!selectyear.hasClass('error') && selectmonth.hasClass('error')) {
            selectyear.parent().find('.select-year').addClass('error');
        }
        else if (selectyear.hasClass('error') && !selectmonth.hasClass('error')) {
            selectmonth.parent().find('.select-month-s').addClass('error');
        }
    });

    $('#State').change(toggleSelect1ErrorMarginTop20);
    //$('#Country').change(toggleSelect1ErrorMarginTop20);

    // Remove text-active style of dropdown
    $(".grouped-form input").removeClass("text-active");
    $(".grouped-form input").click(function () {
        $(this).addClass("text-active");
    });
    $(".grouped-form input").blur(function () {
        $(this).removeClass("text-active");
    });

    if (dataWorkPhoneExt != "") {
        $("#WorkPhoneExt").val(dataWorkPhoneExt);
        $("#WorkPhoneExt").removeClass("text phone-ext text-active").addClass("text");
        //$("#WorkPhoneExt").css("width", "14%");
        $("#WorkPhoneExt").css({ 'width': '14%', 'min-width': '29px', 'float': 'right', 'display': 'block' });
    }
});